<?php
/**
 * Creates the instance of the application
 */
class zapController
{
    /**
	 * Name of current view in use
	 *
     * @var string
     */
    public $zView;

    /**
	 * Name of current action in use
	 *
     * @var string
     */
    public $zAction;

    /**
	 * Name of current controller in use
     *
     * @var string
     */
    public $zController;

    /**
	 * Name of current template in use
     *
     * @var string
     */
    public $zTemplate;

    /**
	 * Instance of the application settings
     *
     * @var array
     */
    public $zapConfig;

    /**
	 * Contains the error message details
     *
     * @var array $error 
     */
    public $zError;

	/**
	 * Instantiate view as an object
	 */
	public function __construct()
	{
        $this->zView = new stdClass();
	}

    /**
     * Constructs the view by applying the set template and passing the view variables from the
	 * action. Returns TRUE when the view is successfully created.
	 *
     * @return boolean
     */
    public function createView()
    {
        /*check if the view file exists*/
        if (!file_exists(ROOT . "application/views/{$this->zController}/{$this->zAction}.view.php")) {
            $this->zError = array(
                'Error'   => 'View not found',
                'Details' => "View for for <strong>{$this->zAction}Action</strong> in the <em>{$this->zController}Controller</em> does not exist."
            );

            return false;
        }

        /*apply templating*/
        if (empty($this->zTemplate)) {
            $this->zapView();
        } else {
            if (file_exists(ROOT . 'application/templates/' . $this->zTemplate)) {
                require_once(ROOT . 'application/templates/' . $this->zTemplate);
            } else {
                $this->zError = array(
                    'Error'   => 'Template file not found',
                    'Details' => "<strong>{$this->zTemplate}</strong> does not exist."
                );

                return false;
            }
        }

        return true;
    }

    /**
     * Creates the instance of the view
     */
    public function zapView()
    {
		if (!empty($this->zView)) {
			foreach ($this->zView as $key => $value) {
				$$key = $value;
			}
		}

		require_once(ROOT . "application/views/{$this->zController}/{$this->zAction}.view.php");
    }

    /**
     * Loads a partial block that can be inserted anywhere within the view or the template
	 *
     * @param string $partial Partial name
     */
    public function zapPartial($partial)
    {
        /*create all the variables passed from the action*/
        if (!empty($this->zView)) {
            foreach ($this->zView as $key => $value) {
                $$key = $value;
            }
        }

        require_once(ROOT . 'application/partials/' . strtolower($partial) . '.partial.php');
    }

    /**
     * Override the default with the specified template file. If blank controller will not render a
	 * template and will directly run the view.
	 *
     * @param string $template Template name
     */
    public function useTemplate($template = false)
    {
        if (empty($template)) {
            $this->zTemplate = '';
        } else {
            $this->zTemplate = $template . '.template.php';
        }
    }

    /**
     * Specifies a view to be used instead of the corresponding action view
	 *
     * @param type $view View name
     */
    public function useView($view)
    {
        $this->zAction = $view;
    }

	/**
	 * Load toolkit class file
	 *
	 * @param string
	 * @return bool
	 */
    public function loadToolkitClass($className)
    {
        if (array_key_exists($className, $this->zapConfig['library'])) {
            require_once(ROOT . 'library/' . $this->zapConfig['library'][$className]);

            return true;
        } else {
            $this->zError = array(
                'Error'   => 'Library class not found',
                'Details' => "The library class <strong>{$className}</strong> does not exist."
            );

            return false;
        }
    }

	/**
	 * Return route based on name or pattern
	 *
	 * @param string $route Name or pattern of route to be returned
	 * @param array $params paramaters to be added in the URL
	 * @return string
	 */
	 public function routeURL($route, $params = array())
	 {
		$route_file = ROOT . 'application/settings/route.ini';
		if (file_exists($route_file)) {
			$routes  = parse_ini_file($route_file, true);
			$pattern = '';

			foreach ($routes as $key => $contents) {
				if ($route == $key) {
					$pattern = $contents['pattern'];
				} else if (strpos($contents['pattern'], $route) == 0) {
					$pattern = $contents['pattern'];
				}
			}

			$segments = array();

			if ($pattern != '') {
				$segments = explode('/', $pattern);

				foreach ($segments as $key => $value) {
					if (strpos($value, ':') !== false) {
						$segment = str_replace(':', '', $value);

						if (array_key_exists($segment, $params)) {
							$segments[$key] = $params[$segment];
						} else {
							unset($segments[$key]);
						}
					}
				}

				return URL . implode('/', $segments);
			} else {
				$this->zError = array(
					'Error'    => 'Route not found',
					'Detailts' => "There was no match found in the applications/settings/route.ini file for the name/pattern {$route}."
				);

				return false;
			}
		}
	 }
}
